package com.wy.controller.wy;

import com.wy.bean.NoticeBean;
import com.wy.constants.CommonValues;
import com.wy.model.sys.NoticeEntity;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.UserService;
import com.wy.service.wy.NoticeRelationService;
import com.wy.service.wy.NoticeService;
import com.wy.utils.BaseResponseInfo;
import com.wy.utils.DateUtils;
import com.wy.utils.FileUtil;
import com.wy.utils.HTTPStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 公告通知管理
 */
@RestController
@RequestMapping("/notices")
@Api(value="API - RestController",tags={"公告通知管理"})
public class NoticeController {

	private Logger log = LoggerFactory.getLogger(NoticeController.class);

	@Resource(name = "noticeServiceImpl")
	private NoticeService noticeService;
	@Resource(name = "noticeRelationServiceImpl")
	private NoticeRelationService noticeRelationService;
	@Resource(name = "userServiceImpl")
	private UserService userService;

	/**
	 * 获取公告列表数据
	 * @param pageSize
	 * @param page
	 * @param content 标题、摘要、内容 模糊搜索
	 * @param type 0维修通知，1水电煤气，2安全提醒，3公益服务，4温馨提示，5紧急通知，6物业费通知单，7其他
	 * @param ntype 1公告2通知
	 * @param publishTimeStart 发布日期开始
	 * @param publishTimeStart 发布日期结束
	 * @param status 状态:0失效，1有效
	 * @return
	 */
	@GetMapping("")
	@ApiOperation(value="noticeList",notes="获取公告列表数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false,dataType = "Int", paramType = "query", defaultValue = "10"),
			@ApiImplicitParam(name = "page", value = "当前页数", required = false,dataType = "Int", paramType = "query",defaultValue = "1"),
			@ApiImplicitParam(name = "content", value = "标题、摘要、内容", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "type", value = "公告类型：0维修通知，1水电煤气，2安全提醒，3公益服务，4温馨提示，5紧急通知，6物业费通知单，7其他", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "ntype", value = "1公告2通知", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "publishTimeStart", value = "发布开始日期", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "publishTimeEnd", value = "发布结束日期", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "status", value = "状态:0待发，1已发，2失效", required = false,dataType = "String", paramType = "query",defaultValue = "")
	})
	public BaseResponseInfo noticeList(HttpServletRequest request, @RequestParam(value = "pageSize",required = false) int pageSize,
									   @RequestParam(value = "page",required = false) int page,
									   @RequestParam(value = "content",required = false) String content,
									   @RequestParam(value = "type",required = false)String type,
									   @RequestParam(value = "ntype",required = false)String ntype,
									   @RequestParam(value = "publishTimeStart",required = false)String publishTimeStart,
									   @RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
									   @RequestParam(value = "status",required = false)String status) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		try {

			List<String> rids = new ArrayList<>();
			UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
			if(null != userEntity) {
				String rid = userEntity.getRid();
				if(!org.apache.commons.lang3.StringUtils.isEmpty(rid)){
					List list = Arrays.asList(rid.split(","));
					rids = new ArrayList(list);
				}
			}
			PageResult pageResult = new PageResult();
			if("admin".equals(userEntity.getLoginName())) {
				rids = null;
			}else {
				rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
			}
			pageResult.setData(noticeService.noticeList(pageSize, page * pageSize, content, type, ntype, publishTimeStart, publishTimeEnd, status,rids));
			pageResult.setTotalCount(noticeService.noticeSize(pageSize, page * pageSize, content, type, ntype, publishTimeStart, publishTimeEnd, status,rids));
			baseResponseInfo.data = pageResult;
		}catch(Exception ex) {
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
			baseResponseInfo.data = ex.getMessage();
			ex.printStackTrace();
		}
		return baseResponseInfo;
	}


	@GetMapping("/app")
	@ApiOperation(value="noticeList",notes="获取公告列表数据-移动端根据用户id获取公告信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false,dataType = "Int", paramType = "query", defaultValue = "10"),
			@ApiImplicitParam(name = "page", value = "当前页数", required = false,dataType = "Int", paramType = "query",defaultValue = "1"),
			@ApiImplicitParam(name = "type", value = "公告类型：0维修通知，1水电煤气，2安全提醒，3公益服务，4温馨提示，5紧急通知，6物业费通知单，7其他", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "ntype", value = "1公告2通知", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "readStatus", value = "0未读1已读", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "uid", value = "用户id", required = false,dataType = "Int", paramType = "query",defaultValue = "")
	})
	public BaseResponseInfo noticeList(@RequestParam(value = "pageSize",required = false) int pageSize,
									   @RequestParam(value = "page",required = false) int page,
									   @RequestParam(value = "type",required = false)String type,
									   @RequestParam(value = "ntype",required = false)String ntype,
									   @RequestParam(value = "readStatus",required = false)String readStatus,
									   @RequestParam(value = "uid",required = false)int uid
		){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		try {
			PageResult pageResult = new PageResult();
			pageResult.setData(noticeService.noticeList(pageSize, page * pageSize, type, ntype,readStatus, uid));
			pageResult.setTotalCount(noticeService.noticeSize(pageSize, page * pageSize, type, ntype,readStatus,uid));
			baseResponseInfo.data = pageResult;
		}catch(Exception ex) {
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
			baseResponseInfo.data = ex.getMessage();
			ex.printStackTrace();
		}
		return baseResponseInfo;
	}

	@PostMapping("/modifyReadStatus")
	@ApiOperation(value="modifyReadStatus",notes="修改公告状态（已读）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "nid", value = "消息id", required = false,dataType = "String", paramType = "query",defaultValue = ""),
			@ApiImplicitParam(name = "uid", value = "用户id", required = false,dataType = "String", paramType = "query",defaultValue = "")
	})
	public BaseResponseInfo modifyReadStatus(@RequestParam(value = "nid",required = false) int id,
									   @RequestParam(value = "uid",required = false)int uid
	){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		try {
			noticeRelationService.modifyReadStatus(id,uid);
		}catch(Exception ex) {
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
			baseResponseInfo.data = ex.getMessage();
			ex.printStackTrace();
		}
		return baseResponseInfo;
	}

	/**
	 * 新建公告通知
	 * @param noticeBean
	 * @return
	 */
	@RequestMapping(value = "/notice", method = RequestMethod.POST)
	@ApiOperation(value="insertNotice",notes="新建公告通知")
	public BaseResponseInfo insertNotice(@RequestBody NoticeBean noticeBean) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String,Object> map = new HashMap<>();
		if(StringUtils.isEmpty(noticeBean.getTitle())) {
			map.put("message","标题不能为空！");
			baseResponseInfo.code = 500;
			baseResponseInfo.data = map;
			return baseResponseInfo;
		}
		if(StringUtils.isEmpty(noticeBean.getSummary())) {
			map.put("message","摘要不能为空！");
			baseResponseInfo.code = 500;
			baseResponseInfo.data = map;
			return baseResponseInfo;
		}
		if(StringUtils.isEmpty(noticeBean.getContent())) {
			map.put("message","内容不能为空！");
			baseResponseInfo.code = 500;
			baseResponseInfo.data = map;
			return baseResponseInfo;
		}
		if(StringUtils.isEmpty(noticeBean.getType())) {
			map.put("message","类型不能为空！");
			baseResponseInfo.code = 500;
			baseResponseInfo.data = map;
			return baseResponseInfo;
		}

		NoticeEntity noticeEntity = new NoticeEntity();
		noticeEntity.setTitle(noticeBean.getTitle());
		noticeEntity.setSummary(noticeBean.getTitle());
		noticeEntity.setContent(noticeBean.getContent());
		noticeEntity.setType(noticeBean.getType());
		noticeEntity.setNtype(noticeBean.getNtype());
		noticeEntity.setCreateTime(new Date());
		noticeEntity.setPublishTime(DateUtils.getFormatDate(noticeBean.getPublishTime(), DateUtils.timeformat4));
		noticeEntity.setInvalidTime(DateUtils.getFormatDate(noticeBean.getInvalidTime(), DateUtils.timeformat4));
		noticeEntity.setPublishUser("admin");
		noticeEntity.setStatus("0");//0待发，1已发，2失效
		noticeEntity.setToUsers(noticeBean.getToUsers());
		noticeEntity.setCreateTime(new Date());
		noticeEntity.setImg1(FileUtil.getFileName(noticeBean.getImg1()));
		noticeEntity.setImg2(FileUtil.getFileName(noticeBean.getImg2()));
		noticeEntity.setImg3(FileUtil.getFileName(noticeBean.getImg3()));
		//保存公告信息
		noticeService.insertNotice(noticeEntity);
//		//保存接收人和公告关系信息
//		JSONArray jsonArray = JSONArray.parseArray(noticeEntity.getToUsers());
//		List<NoticeRelation> list = new ArrayList<>();
//		NoticeRelation noticeRelation = null;
//		for(int i = 0;i < jsonArray.size();i++) {
//			noticeRelation = new NoticeRelation();
//			noticeRelation.setNoticeId(noticeEntity.getId());
//			noticeRelation.setRelationId(jsonArray.getJSONObject(i).getInteger("id"));
//			noticeRelation.setRelationType(jsonArray.getJSONObject(i).getInteger("type"));
//			list.add(noticeRelation);
//		}
//		noticeRelationService.insertBatch(list);
		return baseResponseInfo;
	}

	/**
	 * 修改公告通知
	 * @param noticeEntity
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	@ApiOperation(value="updateNotice",notes="修改公告通知")
	public NoticeEntity updateNotice(@RequestBody NoticeEntity noticeEntity, @PathVariable int id) {
		if (noticeEntity.getId() == id) {
			noticeEntity.setImg1(FileUtil.getFileName(noticeEntity.getImg1()));
			noticeEntity.setImg2(FileUtil.getFileName(noticeEntity.getImg2()));
			noticeEntity.setImg3(FileUtil.getFileName(noticeEntity.getImg3()));
			noticeService.updateNotice(noticeEntity);
		}
		return noticeEntity;
	}

	/**
	 * 删除公告信息
	 * 
	 * @param groupId
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.DELETE)
	@ApiOperation(value="deleteNotice",notes="删除公告信息")
	public void  deleteNotice(@RequestBody List<String> groupId) {
		//删除通知公告
		noticeService.deleteNotice(groupId);
		//删除关联关系
		noticeRelationService.deleteNoticeRelation(groupId);
	}

}
